package com.liyao.windowtest4.controller;

import com.liyao.windowtest4.Utils.SharedModel;
import com.liyao.windowtest4.pojo.Routine;
import com.liyao.windowtest4.pojo.torqueRow;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import javafx.util.StringConverter;
import javafx.util.converter.NumberStringConverter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.UUID;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-10-24 14:00
 */
public class createProgramController implements Initializable {

    @FXML
    public TableView<torqueRow> torqueView;
    @FXML
    public TextField RoutineName;
    public int torqueNum;

    public String addTime;

    public String torqueContent;

    public String uniqueValue;

    private boolean isAdd=false;

    public boolean isAdd() {
        return isAdd;
    }

    private String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;

    @FXML
    private ObservableList<torqueRow> data = FXCollections.observableArrayList();
    @FXML
    public void createTorque(ActionEvent actionEvent) {
        try {
            // 加载FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/torqueProgram.fxml"));
            AnchorPane vbox = loader.load();

            // 创建新窗口
            Stage formStage = new Stage();
            formStage.initModality(Modality.APPLICATION_MODAL);
            formStage.initStyle(StageStyle.UTILITY);
            formStage.setTitle("扭矩设置");

//            // 设置新窗口的场景
            Scene formScene = new Scene(vbox);
            formStage.setScene(formScene);
            formStage.showAndWait();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        data = SharedModel.getInstance().getTableData();
        // 初始化表格列

        TableColumn<torqueRow, Integer> serialNumber = new TableColumn<>("序号");
        serialNumber.setCellValueFactory(new Callback<>() {
            @Override
            public ObservableValue<Integer> call(TableColumn.CellDataFeatures<torqueRow, Integer> torqueRowIntegerCellDataFeatures) {
                int index = torqueRowIntegerCellDataFeatures.getTableView().getItems().indexOf(torqueRowIntegerCellDataFeatures.getValue()) + 1;
                return new SimpleIntegerProperty(index).asObject();
            }
        });

        TableColumn<torqueRow, Double> TorqueMin = new TableColumn<>("扭矩下限");
        TorqueMin.setCellValueFactory(new PropertyValueFactory<>("TorqueMin"));

        TableColumn<torqueRow, Double> TorqueTarget = new TableColumn<>("目标扭矩");
        TorqueTarget.setCellValueFactory(new PropertyValueFactory<>("TorqueTarget"));

        TableColumn<torqueRow, Double> TorqueMax = new TableColumn<>("扭矩上限");
        TorqueMax.setCellValueFactory(new PropertyValueFactory<>("TorqueMax"));

        TableColumn<torqueRow, Double> AngleMin = new TableColumn<>("角度下限");
        AngleMin.setCellValueFactory(new PropertyValueFactory<>("AngleMin"));

        TableColumn<torqueRow, Double> AngleTarget = new TableColumn<>("目标角度");
        AngleTarget.setCellValueFactory(new PropertyValueFactory<>("AngleTarget"));

        TableColumn<torqueRow, Double> AngleMax = new TableColumn<>("角度上限");
        AngleMax.setCellValueFactory(new PropertyValueFactory<>("AngleMax"));

        TableColumn<torqueRow, Double> StartAngle = new TableColumn<>("贴合扭矩");
        StartAngle.setCellValueFactory(new PropertyValueFactory<>("StartAngle"));

        // 新增一个操作列
        TableColumn<torqueRow, Void> actionColumn = new TableColumn<>("操作");
        actionColumn.setPrefWidth(100); // 可根据需要设置列宽
        actionColumn.setCellFactory(column -> new TableCell<torqueRow, Void>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || isEmpty()) { // 使用isEmpty()来检查单元格是否为空
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox hbox = new HBox(10);
                    Button viewButton = new Button("编辑");
                    Button deleteButton = new Button("删除");
                    // 设置按钮的尺寸
                    viewButton.setPrefWidth(50); // 设置首选宽度为100
                    viewButton.setMaxWidth(100);  // 设置最大宽度为200
                    viewButton.setMinWidth(30);   // 设置最小宽度为50
                    viewButton.setFont(new Font(9)); // 只指定大小，使用默认字体和样式

                    deleteButton.setPrefWidth(50); // 设置首选宽度为100
                    deleteButton.setMaxWidth(100);  // 设置最大宽度为200
                    deleteButton.setMinWidth(30);   // 设置最小宽度为50
                    deleteButton.setFont(new Font(9));

                    // 你也可以设置高度，如果需要的话
                    viewButton.setPrefHeight(20);
                    deleteButton.setPrefHeight(20);

                    viewButton.getStyleClass().add("edit-button-style");
                    deleteButton.getStyleClass().add("delete-button-style");

                    // 使用getTableRow().getItem()来获取当前行的数据
                    // 注意：这种方法在某些情况下可能不起作用，特别是当表格处于虚拟滚动时
                    final torqueRow currentRowItem = getTableRow() != null ? getTableRow().getItem() : null;

                    deleteButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            System.out.println(currentRowItem.getAngleMax());
                            data.remove(currentRowItem);
                        }
                    });

                    viewButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            // 创建B页面的控制器和FXMLLoader
                            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/EditTorqueProgram.fxml"));
                            Parent bPageRoot = null;
                            try {
                                bPageRoot = loader.load();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            EditTorqueProgramController bController = loader.getController();
                            // 将数据传递给B页面的控制器
                            bController.setDataItem(currentRowItem);

                            // 创建一个新的Stage或Dialog来显示B页面
                            Stage stage = new Stage();
                            stage.initModality(Modality.APPLICATION_MODAL);
                            stage.initStyle(StageStyle.UTILITY);
                            stage.setTitle("编辑");
                            stage.setScene(new Scene(bPageRoot));
                            stage.showAndWait();
                            torqueView.refresh();
                        }
                    });

                    hbox.getChildren().addAll(viewButton,deleteButton);
                    setGraphic(hbox);
                }
            }
        });

        torqueView.getColumns().addAll(serialNumber,TorqueMin,TorqueTarget,TorqueMax,AngleMin,AngleTarget,AngleMax,StartAngle,actionColumn);

        torqueView.setItems(data);

        clearTableData();

    }

    public void clearTableData() {
        data.clear();
    }

    // 添加数据到表格的方法
    public void addDataToTable(torqueRow newData) {
        SharedModel.getInstance().getTableData().add(newData);
    }

    @FXML
    public void HandleSubmit(ActionEvent actionEvent) {
        ObservableList<torqueRow> allItems = torqueView.getItems();
        this.torqueNum= allItems.size();
        if(RoutineName.getText().length()==0){
            showAlert(Alert.AlertType.ERROR,"验证错误", "请填写所有必填项","请填写程序名称");
        } else if (allItems.size() == 0) {
            showAlert(Alert.AlertType.ERROR,"验证错误", "请填写所有必填项","请至少添加一个螺栓");
        } else{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            this.addTime=sdf.format(new Date());
            JSONObject js=new JSONObject();
            JSONArray arr=new JSONArray();
            JSONObject json=new JSONObject();
            // 处理所有项
            allItems.forEach(t -> {
                        js.put("TorqueMin",t.getTorqueMin());
                        js.put("AngleTarget",t.getAngleTarget());
                        js.put("TorqueMax",t.getTorqueMax());
                        js.put("AngleMin",t.getAngleMin());
                        js.put("TorqueTarget",t.getTorqueTarget());
                        js.put("AngleMax",t.getAngleMax());
                        js.put("StartAngle",t.getStartAngle());
                        arr.add(js);
                    }
            );
            this.uniqueValue = String.format("%d",Instant.now().toEpochMilli());
            json.put("code",uniqueValue);
            json.put("RoutineName",RoutineName.getText());
            json.put("TorqueNum",allItems.size());
            json.put("addTime",addTime);
            json.put("content",arr);
            this.torqueContent=arr.toString();


            // 定义要写入的文件路径
            String filePath = configDirPath+"Routine.txt"; // 文件路径

            // 将数据（包括新添加的数据）写入文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
                // 遍历数据列表并写入文件
                writer.write(json.toString());
                writer.newLine();
                System.out.println("写入Routine文件成功,write ok!");
                this.isAdd=true;
                Stage stage = (Stage) ((Button) actionEvent.getSource()).getScene().getWindow();
                stage.close();
            } catch (IOException e) {
                e.printStackTrace(); // 打印错误堆栈信息到控制台（通常不推荐在生产环境中这样做）
                // 在实际应用中，您应该使用更用户友好的错误处理方式，比如显示一个错误消息对话框
                this.isAdd=false;
            }
        }

    }

    public Routine getNewData() {
        Routine newData = new Routine(this.uniqueValue,RoutineName.getText(),this.torqueNum,this.addTime,this.torqueContent);
        return newData;
    }

    private void showAlert(Alert.AlertType alertType, String title, String headerText,String ContentText) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(ContentText); // 可以根据需要自定义内容文本
        alert.showAndWait(); // 显示对话框并等待用户响应
    }
}
